<template>
  <div class="uploader">
    <el-upload
      ref="uploader"
      class="upload-demo"
      action="#"
      :http-request="customRequest"
      :show-file-list="false"
      :disabled="disabled"
    >
      <!-- :on-remove="handleRemove"
      :before-remove="beforeRemove" -->
      <el-button
        :disabled="disabled"
        type="success"
        round
      ><i class="el-icon-upload el-icon--right" />上传</el-button>
      <!-- <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div> -->
    </el-upload>
    <table v-if="files.length > 0" class="com-table" style="margin-top: 10px">
      <tr>
        <td class="com-td">文件名</td>
        <td class="com-td">备注</td>
        <td class="com-td" style="width:280">操作</td>
      </tr>
      <tr v-for="item in files" :key="item.name">
        <td class="com-td" style="width:280">
          <a :class="{ 'com-link': canDownload }" @click="downLoad(item)">{{
            item.name
          }}</a>
        </td>
        <td class="com-td">
          <el-input v-model="item.remark" :disabled="disabled" size="small" />
        </td>
        <td class="com-btn">
          <el-button
            type="success"
            size="mini"
            @click="preview2(item)"
          >预览</el-button>
          <el-button
            type="primary"
            size="mini"
            @click="downLoad(item)"
          >下载</el-button>
          <el-button
            :disabled="disabled"
            type="danger"
            size="mini"
            @click="delfile(item)"
          >删除</el-button>
        </td>
      </tr>
    </table>
    <!-- <el-table
      :data="files"
      style="width: 100%"
    >
      <el-table-column
        label="备注"
        width="180"
      >
        <template slot-scope="{row : {remark}}">
          <el-input v-model="remark" type="textarea" />
        </template>
      </el-table-column>
    </el-table> -->
  </div>
</template>

<script>
import { uploadSingleFile } from '@/api/common'
export default {
  name: 'Uploader',
  components: {},
  model: {
    prop: 'fileList',
    event: 'change'
  },
  props: {
    fileList: {
      type: Array,
      default() {
        return []
      }
    },
    canDownload: {
      type: Boolean,
      default: false
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      files: []
    }
  },
  watch: {
    files: {
      handler(newVal) {
        this.$emit('change', newVal)
      },
      deep: true
    },
    fileList: {
      handler(val) {
        this.files = val
      },
      immediate: true
    }
  },
  methods: {
    downLoad(item) {
      if (item.relativelyPath) {
        this.$emit('download', item)
        fetch(item.relativelyPath).then(res => res.blob().then(blob => {
          var a = document.createElement('a')
          var url = window.URL.createObjectURL(blob)
          var filename = item.name
          a.href = url
          a.download = filename
          a.click()
          window.URL.revokeObjectURL(url)
        }))
      }
    },
    customRequest(params) {
      const { file } = params
      const formData = new FormData()
      formData.append('file', file)
      uploadSingleFile(formData).then((res) => {
        if (res.code === '0001') {
          this.$refs.uploader.clearFiles()
          this.$message({
            type: 'success',
            message: '上传成功'
          })
          const files = JSON.parse(JSON.stringify(this.fileList))
          files.push({
            name: file.name,
            relativelyPath: res.data,
            remark: ''
          })
          this.files = files
        } else {
          this.$message({
            type: 'error',
            message: res.msg || '上传成功'
          })
        }
      })
    },
    delfile(item) {
      const index = this.files.indexOf(item)
      this.files.splice(index, 1)
    },
    preview2(row) {
      this.$emit('preview', row)
      const type = this.matchFileType(row.relativelyPath)
      if (type === 'pdf' || type === 'image') {
        const routeUrl = this.$router.resolve({
          path: '/viewFiles/pdf',
          query: { url: row.relativelyPath }
        })
        window.open(routeUrl.href, '_blank')
      } else {
        const fileMapPath = this.getFileMapPath(row.relativelyPath)
        const routeUrl = this.$router.resolve({
          path: '/viewFiles/word',
          query: { url: fileMapPath }
        })
        window.open(routeUrl.href, '_blank')
      }
    },
    // 获取文件映射路径
    getFileMapPath(fileName) {
      const find = 'file' // 查找特征码
      const index = fileName.indexOf(find) // 特征码索引
      const mapPath = fileName.substr(index + find.length) // 截取文件定位地址
      const domainPath = 'http://www.mchylq.cn/preview/' + mapPath // 域名地址

      return domainPath
    },
    matchFileType(fileName) {
      // 后缀获取
      let suffix = ''
      // 获取类型结果
      let result = ''
      if (!fileName) return false
      try {
        // 截取文件后缀
        suffix = fileName.substr(
          fileName.lastIndexOf('.') + 1,
          fileName.length
        )
        // 文件后缀转小写，方便匹配
        suffix = suffix.toLowerCase()
      } catch (err) {
        suffix = ''
      }
      // fileName无后缀返回 false
      if (!suffix) {
        result = false
        return result
      }

      const fileTypeList = [
        // 图片类型
        { typeName: 'image', types: ['png', 'jpg', 'jpeg', 'bmp', 'gif'] },
        // 文本类型
        { typeName: 'txt', types: ['txt'] },
        // excel类型
        { typeName: 'excel', types: ['xls', 'xlsx'] },
        { typeName: 'word', types: ['doc', 'docx', 'docm'] },
        { typeName: 'pdf', types: ['pdf'] },
        { typeName: 'ppt', types: ['ppt'] },
        // 视频类型
        { typeName: 'video', types: ['mp4', 'm2v', 'mkv'] },
        // 音频
        { typeName: 'radio', types: ['mp3', 'wav', 'wmv'] }
      ]
      // let fileTypeList = ['image', 'txt', 'excel', 'word', 'pdf', 'video', 'radio']
      for (let i = 0; i < fileTypeList.length; i++) {
        const fileTypeItem = fileTypeList[i]
        const typeName = fileTypeItem.typeName
        const types = fileTypeItem.types
        result = types.some(function(item) {
          return item === suffix
        })
        if (result) {
          return typeName
        }
      }
      return 'other'
    }
  }
}
</script>

<style lang="scss" scoped>
.el-upload {
  display: flex !important;
}
.com-table {
  border-collapse: collapse;
  border: 1px solid #dedede;
  .com-td {
    border: 1px solid #dedede !important;
    padding:10px;
  }
  .com-btn {
    border: 1px solid #dedede;
    padding: 10px;
  }
}
</style>
